<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>虚拟奶龙 - 对话</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FFD166', // 主色调：奶龙黄
                        secondary: '#06D6A0', // 辅助色：薄荷绿
                        neutral: '#F7FFF7', // 中性色：浅灰白
                        dark: '#292F36', // 深色：深灰
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .bg-gradient-custom {
                background: linear-gradient(135deg, #FFD166 0%, #FFAA00 100%); /* 黄色渐变 */
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .message-appear {
                animation: fadeIn 0.3s ease forwards;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .typing-animation span {
                animation: typing 1.4s infinite both;
                display: inline-block;
                width: 8px;
                height: 8px;
                margin: 0 2px;
                border-radius: 50%;
                background: #888;
            }
            .typing-animation span:nth-child(2) {
                animation-delay: 0.2s;
            }
            .typing-animation span:nth-child(3) {
                animation-delay: 0.4s;
            }
            @keyframes typing {
                0% { transform: translateY(0); }
                50% { transform: translateY(-5px); }
                100% { transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-neutral min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-md sticky top-0 z-50 transition-all duration-300" id="navbar">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <a href="#" class="flex-shrink-0 flex items-center">
                        <i class="fa fa-dragon text-primary text-2xl mr-2"></i>
                        <span class="font-bold text-xl text-dark">虚拟奶龙</span>
                    </a>
                </div>
                <div class="flex items-center space-x-2">
                    <span class="text-sm text-gray-600">欢迎回来，{{ username }}</span>
                    <a href="{{ url_for('logout') }}" class="text-red-500 hover:text-red-600 px-3 py-2 rounded-md text-sm font-medium transition-colors duration-200">
                        <i class="fa fa-sign-out"></i> 退出
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="flex-grow flex items-center justify-center p-4">
        <div class="w-full max-w-4xl">
            <div class="bg-white rounded-xl shadow-lg overflow-hidden h-[80vh] flex flex-col transform transition-all duration-500 card-hover">
                <!-- 聊天头部 -->
                <div class="bg-gradient-custom p-4 text-white flex items-center">
                    <div class="relative">
                        <img src="{{ url_for('static', filename='images/nailong.png') }}" alt="虚拟奶龙头像" class="w-12 h-12 rounded-full object-cover border-2 border-white">
                        <span class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-white"></span>
                    </div>
                    <div class="ml-3">
                        <h3 class="font-bold text-lg">虚拟奶龙</h3>
                        <p class="text-sm text-white/80">正在在线，随时为你服务</p>
                    </div>
                </div>

                <!-- 聊天历史 -->
                <div id="chat-history" class="flex-grow overflow-y-auto p-4 space-y-4 scrollbar-hide">
                    <div class="flex items-start">
                        <img src="{{ url_for('static', filename='images/nailong.png') }}" alt="虚拟奶龙头像" class="w-10 h-10 rounded-full object-cover">
                        <div class="ml-3 max-w-[80%]">
                            <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 shadow-sm message-appear">
                                <p>你好！我是虚拟奶龙，很高兴见到你！有什么我可以帮助你的吗？</p>
                            </div>
                            <span class="text-xs text-gray-500 mt-1">刚刚</span>
                        </div>
                    </div>

                    <!-- 历史消息 -->
                    {% for message in history %}
                        {% if message.role == 'user' %}
                            <div class="flex items-start justify-end">
                                <div class="mr-3 max-w-[80%]">
                                    <div class="bg-primary text-dark rounded-lg rounded-tr-none p-3 shadow-sm message-appear">
                                        <p>{{ message.message }}</p>
                                    </div>
                                    <div class="flex justify-end">
                                        <span class="text-xs text-gray-500 mt-1">{{ message.timestamp.strftime('%Y-%m-%d %H:%M') }}</span>
                                    </div>
                                </div>
                                <img src="{{ url_for('static', filename='images/user.png') }}" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
                            </div>
                        {% else %}
                            <div class="flex items-start">
                                <img src="{{ url_for('static', filename='images/nailong.png') }}" alt="虚拟奶龙头像" class="w-10 h-10 rounded-full object-cover">
                                <div class="ml-3 max-w-[80%]">
                                    <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 shadow-sm message-appear">
                                        <p>{{ message.message }}</p>
                                    </div>
                                    <span class="text-xs text-gray-500 mt-1">{{ message.timestamp.strftime('%Y-%m-%d %H:%M') }}</span>
                                </div>
                            </div>
                        {% endif %}
                    {% endfor %}

                    <!-- 打字动画占位 -->
                    <div id="typing-indicator" class="flex items-start hidden">
                        <img src="{{ url_for('static', filename='images/nailong.png') }}" alt="虚拟奶龙头像" class="w-10 h-10 rounded-full object-cover">
                        <div class="ml-3 max-w-[80%]">
                            <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 shadow-sm">
                                <div class="typing-animation">
                                    <span></span>
                                    <span></span>
                                    <span></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="p-4 border-t border-gray-200">
                    <form id="message-form" class="flex space-x-2">
                        <input type="text" id="message-input" placeholder="输入消息..."
                            class="flex-grow rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 focus:ring-opacity-50 transition-all duration-200 px-4 py-2"
                            required>
                        <button type="submit" class="bg-primary hover:bg-primary/90 text-dark rounded-lg px-4 py-2 transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98]">
                            <i class="fa fa-paper-plane"></i> 发送
                        </button>
                    </form>
                    <div class="flex justify-between items-center mt-2 text-xs text-gray-500">
                        <div>
                            <button id="clear-history" class="hover:text-primary transition-colors duration-200">
                                <i class="fa fa-trash-o mr-1"></i> 清空历史
                            </button>
                        </div>
                        <div>
                            <span id="char-count">0/200</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white py-6">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <div class="flex items-center">
                        <i class="fa fa-dragon text-primary text-xl mr-2"></i>
                        <span class="font-bold text-lg">虚拟奶龙</span>
                    </div>
                    <p class="text-white/70 text-sm mt-1">让对话更加有趣</p>
                </div>
                <div class="flex space-x-4">
                    <a href="#" class="text-white/70 hover:text-primary transition-colors duration-200">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                    <a href="#" class="text-white/70 hover:text-primary transition-colors duration-200">
                        <i class="fa fa-twitter text-xl"></i>
                    </a>
                    <a href="#" class="text-white/70 hover:text-primary transition-colors duration-200">
                        <i class="fa fa-weixin text-xl"></i>
                    </a>
                </div>
            </div>
            <div class="mt-6 pt-6 border-t border-white/10 text-center text-white/50 text-sm">
                <p>© 2025 第12组【我是奶龙】. 保留所有权利.</p>
            </div>
        </div>
    </footer>

    <script>
        // 导航栏滚动效果
        window.addEventListener('scroll', function() {
            const navbar = document.getElementById('navbar');
            if (window.scrollY > 10) {
                navbar.classList.add('bg-white/95', 'backdrop-blur-sm');
                navbar.classList.remove('bg-white');
            } else {
                navbar.classList.add('bg-white');
                navbar.classList.remove('bg-white/95', 'backdrop-blur-sm');
            }
        });

        // 消息发送
        document.getElementById('message-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const messageInput = document.getElementById('message-input');
            const message = messageInput.value.trim();

            if (message) {
                // 添加用户消息到界面
                addMessageToUI(message, 'user');

                // 显示打字动画
                document.getElementById('typing-indicator').classList.remove('hidden');

                // 滚动到底部
                scrollToBottom();

                // 发送消息到服务器
                fetch('/send_message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message }),
                })
                .then(response => response.json())
                .then(data => {
                    // 隐藏打字动画
                    document.getElementById('typing-indicator').classList.add('hidden');

                    // 添加机器人回复到界面
                    addMessageToUI(data.message, 'bot');

                    // 滚动到底部
                    scrollToBottom();
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('typing-indicator').classList.add('hidden');
                    addMessageToUI('抱歉，发生了错误，请稍后再试。', 'bot');
                    scrollToBottom();
                });

                // 清空输入框
                messageInput.value = '';
                updateCharCount();
            }
        });

        // 字符计数
        document.getElementById('message-input').addEventListener('input', updateCharCount);

        function updateCharCount() {
            const input = document.getElementById('message-input');
            const count = input.value.length;
            document.getElementById('char-count').textContent = `${count}/200`;

            if (count > 200) {
                document.getElementById('char-count').classList.add('text-red-500');
            } else {
                document.getElementById('char-count').classList.remove('text-red-500');
            }
        }

        // 清空历史
        document.getElementById('clear-history').addEventListener('click', function() {
            if (confirm('确定要清空所有聊天历史吗？')) {
                // 清空界面
                const chatHistory = document.getElementById('chat-history');
                // 保留欢迎消息
                const firstChild = chatHistory.firstElementChild;
                chatHistory.innerHTML = '';
                chatHistory.appendChild(firstChild);

                // 发送请求到服务器删除历史
                fetch('/clear_history', {
                    method: 'POST',
                })
                .then(response => {
                    if (response.ok) {
                        alert('聊天历史已清空');
                    } else {
                        alert('清空历史失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('发生错误，请重试');
                });
            }
        });

        // 添加消息到界面
        function addMessageToUI(message, role) {
            const chatHistory = document.getElementById('chat-history');
            const messageDiv = document.createElement('div');

            if (role === 'user') {
                messageDiv.className = 'flex items-start justify-end';
                messageDiv.innerHTML = `
                    <div class="mr-3 max-w-[80%]">
                        <div class="bg-primary text-dark rounded-lg rounded-tr-none p-3 shadow-sm opacity-0" style="animation: fadeIn 0.3s ease forwards 0.1s;">
                            <p>${escapeHTML(message)}</p>
                        </div>
                        <div class="flex justify-end">
                            <span class="text-xs text-gray-500 mt-1">刚刚</span>
                        </div>
                    </div>
                    <img src="{{ url_for('static', filename='images/user.png') }}" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
                `;
            } else {
                messageDiv.className = 'flex items-start';
                messageDiv.innerHTML = `
                    <img src="{{ url_for('static', filename='images/nailong.png') }}" alt="虚拟奶龙头像" class="w-10 h-10 rounded-full object-cover">
                    <div class="ml-3 max-w-[80%]">
                        <div class="bg-gray-100 rounded-lg rounded-tl-none p-3 shadow-sm opacity-0" style="animation: fadeIn 0.3s ease forwards 0.1s;">
                            <p>${escapeHTML(message)}</p>
                        </div>
                        <span class="text-xs text-gray-500 mt-1">刚刚</span>
                    </div>
                `;
            }

            chatHistory.appendChild(messageDiv);
        }

        // 滚动到底部
        function scrollToBottom() {
            const chatHistory = document.getElementById('chat-history');
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        // HTML 转义
        function escapeHTML(str) {
            return str
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        // 页面加载完成后滚动到底部
        document.addEventListener('DOMContentLoaded', function() {
            scrollToBottom();
        });
    </script>
</body>
</html>